﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using repliback4.Net.Protocol.States;
using System.Reflection;

namespace repliback4.Net.Protocol.SASLMechanisms {
    public class MechanismsRegistryEntry {
        protected String name;
        protected Boolean enabled = true;
        protected Type handlingState;
        public Boolean Enabled {
            get { return this.enabled; }
            set { this.enabled = value; }
        }
        public String Name {
            set { this.name = value; }
            get { return this.name; }
        }
        public Type HandlingState {
            set { this.handlingState = value; }
            get { return this.handlingState; }
        }
        public State GetHandlingState ( StateManager manager ) {
            ConstructorInfo cInfo = this.handlingState.GetConstructor( new Type[] { typeof( StateManager ) } );
            if ( cInfo != null ) {
                return cInfo.Invoke( new object[] { manager } ) as State;
            } else {
                throw new Exception( "proper constructor not found" );
            }

        }
    }





    public class MechanismsRegistry : Registry<MechanismsRegistryEntry> {

        public MechanismsRegistry ( ) {

        }
        public MechanismsRegistryEntry LookupByName ( String name ) {
            return list.Find( new Predicate<MechanismsRegistryEntry>(
                ( MechanismsRegistryEntry entry ) => entry.Name == name && entry.Enabled
                ) );
        }

        public List<MechanismsRegistryEntry> GetEnabledMechanisms ( ) {
            return this.list.FindAll( new Predicate<MechanismsRegistryEntry>(
                ( MechanismsRegistryEntry entry ) => entry.Enabled
                ) );
        }


        public static MechanismsRegistry Default {
            get {
                MechanismsRegistry reg = new MechanismsRegistry( );
                reg.Register( new MechanismsRegistryEntry( ) {
                    Name = "PLAIN",
                    HandlingState = typeof( repliback4.Net.Protocol.States.ServerSide.PLAIN_SASLAuthorizingState )
                } );
                reg.Register( new MechanismsRegistryEntry( ) {
                    Name = "DIGEST-MD5",
                    HandlingState = typeof( repliback4.Net.Protocol.States.ServerSide.DIGESTMD5_SASLAuthorizingState ),
                    Enabled = false
                } );
                return reg;
            }
        }
    }
}
